package com.uuuo.rxjavaandretrofit;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.uuuo.rxjavaandretrofit.adapter.MyConverterFactory;
import com.uuuo.rxjavaandretrofit.gson.DateTypeAdapter;

import java.util.Date;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by JiaTao on 2018/9/10.
 * Email: 535318720@qq.com
 * Version: 1.0
 * Description:
 */
public class RetrofitManage {
    private final String BASE_URL = "http://10.2.1.151:8080/";

    private volatile static RetrofitManage sInstance;
    private Retrofit mRetrofit;
    private UserService mUserService;

    private RetrofitManage() {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String messae) {
                Log.e("******OKHttp******", messae);
            }
        });
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)
                .build();

        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setDateFormat("yyyy-MM-dd");
        gsonBuilder.registerTypeAdapter(Date.class,new DateTypeAdapter());
        Gson gson = gsonBuilder.create();

        mRetrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(BASE_URL)
                .addConverterFactory(new MyConverterFactory())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        mUserService = mRetrofit.create(UserService.class);
    }

    public static RetrofitManage getInstance() {
        if (sInstance == null) {
            synchronized (RetrofitManage.class) {
                if (sInstance == null) {
                    sInstance = new RetrofitManage();
                }
            }
        }
        return sInstance;
    }

    public UserService getUserService() {
        return mUserService;
    }
}
